<template>
  <a-drawer
      title="表头显示调整"
      :width="680"
      :open="visible"
      :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 55px)',  // Subtract header height
      overflow: 'auto'             // Enable scrolling
    }"
      @close="close"
  >
    <div :style="{ minHeight: '100%' }">  <!-- Ensures content fills space -->
      <DraggableEditableTable
          ref="configTable"
          :columns="columns"
          :initialData="configData"
          :showDragHandle="true"
          :deletable="canAddPrimaryKey"
          :showAddRow="canAddPrimaryKey"
          @update:data="onDataUpdate"
      />
    </div>

    <div
        :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <!-- Buttons remain fixed at bottom -->
      <a-button :style="{ marginRight: '8px' }" @click="handleApply">应用</a-button>
      <a-button type="primary" :style="{ marginRight: '8px' }" @click="handleSave">保存</a-button>
      <!--      <a-button danger :style="{ marginRight: '8px' }" @click="handleCancel">还原</a-button>-->
      <a-button type="primary" danger @click="handleReset">重置</a-button>
    </div>
  </a-drawer>
</template>

<script setup>
import {ref, watchEffect} from 'vue';
import { DeleteOutlined } from '@ant-design/icons-vue';
import DraggableEditableTable from '@/components/YGCrm/DraggableEditableTable.vue';
import { FormTypes } from "@/utils/JEditableTableUtil.js";
import { getJsonSetting, saveJsonSetting } from "@/utils/api.js";
import { message } from 'ant-design-vue';
import useUserStore from "@/store/modules/user.js";

/* store */
const currentUser = useUserStore()
/* props */
const props = defineProps({
  visible:{
    type: Boolean,
    default: true
  },
  keyId:{
    type: String,
    required: true
  },
  originalConfigData:{
    type: Array,
    default: () => []
  },
  currentConfigData:{
    type: Array,
    default: () => []
  }
});

/* data */
const result = ref([])
const configTable = ref(null)
const original_dataIndexAll =  props.originalConfigData.map((item)=>item.dataIndex)
const current_dataIndexAll =  props.currentConfigData.map((item)=>item.dataIndex)
const primaryKeyOptions = ref([])
const canAddPrimaryKey = ref(false)
watchEffect(()=>{
  primaryKeyOptions.value = props.originalConfigData.filter((item)=>item.dataIndex!=="action" && item.title!=="#").map((c)=> {
    if(!current_dataIndexAll.includes(c.dataIndex) && !canAddPrimaryKey.value){ //模型中的字段，有一个或多个在生效字段中不存在时，
      canAddPrimaryKey.value = true
    }
    return {label: c.dataIndex, value: c.dataIndex}
  })
})
// primaryKeyOptions.value.push({label: 'test', value: 'test'})
// 表格列配置（移除 customDisplay）
const columns = ref([
  {
    title: '可显示',
    dataIndex: 'visible',
    type: FormTypes.checkbox,
    width: 85,
    align: 'center',
    defaultValue: true
  },
  {
    title: '可排序',
    dataIndex: 'sorter',
    type: FormTypes.checkbox,
    width: 80,
    align: 'center'
  },
  {
    title: '显示名称',
    dataIndex: 'title',
    type: FormTypes.input, // 点击可编辑
    width: 150
  },
  {
    title: '字段ID',
    dataIndex: 'dataIndex',
    type: FormTypes.sel_search,
    width: 180,
    options: primaryKeyOptions,
    validateRules:[
      {pattern: 'uniq', message: '字段名称不能重复'}
    ],
  },
  {
    title: '显示宽度',
    dataIndex: 'width',
    type: FormTypes.input, // 点击可编辑
    validateRules:[
      {pattern: 'n-%', message: '请输入数字或百分比'}
    ],
    width: 100,
    align: 'right'
  },
  { title: '位置',
    dataIndex: 'align',
    type: FormTypes.select,
    defaultValue: 'center',
    align: 'center',
    options: [
      { label: '靠左', value: 'left' },
      { label: '靠右', value: 'right' },
      { label: '居中', value: 'center' },
    ],
    width: 80
  }
]);

const configData = computed(()=>{
  return props.currentConfigData.filter((item)=>item.dataIndex!=="action" && item.title!=="#" && original_dataIndexAll.includes(item.dataIndex))
})
console.error("primaryKeyOptions:",JSON.stringify(primaryKeyOptions.value))
console.error("c:",canAddPrimaryKey.value)
// 新增表头项
const addNewItem = () => {
  configTable.value.addNewRow();
};
const handleApply = () => {
  configTable.value.apply();
};
const handleSave = () => {
  configTable.value.apply();
  console.error("props", JSON.stringify(props))
  saveJsonSetting({
    type: 'columns_layout',
    key: props.keyId,
    value: JSON.stringify(result.value),
    update_by: currentUser.name
  }).catch((err)=>{
    console.error("saveJsonSetting error:", err)
    message.error("保存失败")
  }).then((res)=>{
    if(res && res.success)
      message.success("保存成功")
    else
      message.error("保存失败")
  })
};
const handleCancel = () => {
  configTable.value.rollback();
};
const handleReset = () => {

};
const close = () => {
  emit('close');
};
const onDataUpdate = (data) => {
  //props.currentConfigData = data
  result.value = data
  emit('update:data', data)
}
const emit = defineEmits([
  'update:data',
  'close'
]);
</script>

<style scoped>
.header-config-page {
  max-width: 800px;
  margin: 32px auto;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

h2 {
  margin-bottom: 24px;
  font-size: 18px;
  font-weight: 600;
}

.preview {
  margin-top: 24px;
  padding: 16px;
  background: #f9fafb;
  border: 1px solid #eee;
  border-radius: 4px;
}

.preview h3 {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
}

.preview pre {
  margin: 0;
  font-size: 12px;
  white-space: pre-wrap;
}
</style>